package helper

import (
	"encoding/hex"
	"github.com/tjfoc/gmsm/sm4"
)

func SM4EcbDecrypt(key []byte, data string) ([]byte, error) {
	plaintext, _ := hex.DecodeString(data)
	block, err := sm4.NewCipher(key)
	if err != nil {
		return nil, err
	}

	ciphertext := make([]byte, len(plaintext))

	for start := 0; start < len(plaintext); start += block.BlockSize() {
		block.Decrypt(ciphertext[start:start+block.BlockSize()], plaintext[start:start+block.BlockSize()])
	}
	ciphertext = PKCS5Unpadding(ciphertext)
	return ciphertext, nil
}

func PKCS5Unpadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}
